package jhunter.security;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import jhunter.dao.DaoFactory;
import jhunter.dao.DataAccess;
import jhunter.dao.bo.BaseObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class JHunterAuthorizingRealm extends AuthorizingRealm {

	private DaoFactory daoFactory;
	
	private String userEntityId = "User";

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String username = upToken.getUsername();
		String password = new String(upToken.getPassword());
		// Null username is invalid
		if (StringUtils.isEmpty(username)|| StringUtils.isEmpty(password)) {
			throw new AccountException("Null usernames or password are not allowed by this realm.");
		}
		DataAccess dao = daoFactory.getDao(userEntityId);
		BaseObject example = BaseObject.create().addValue("username", username).addValue("password", password);
		List<BaseObject> list = dao.query(dao.createExample(example));
		if(list == null || list.size() != 1) {
			throw new AuthenticationException("账号或密码错误.");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
		return info;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		 //null usernames are invalid
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        String username = (String) getAvailablePrincipal(principals);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> ps = new HashSet<String>();
        ps.add("*");
        info.setStringPermissions(ps);
		return info;
	}

	public DaoFactory getDaoFactory() {
		return daoFactory;
	}

	public void setDaoFactory(DaoFactory daoFactory) {
		this.daoFactory = daoFactory;
	}

}
